Imports System.IO
Imports System.Collections.Generic
Imports Cdm.AppServices.Log
Imports Cdm.DataCore
Imports Cdm.DataCore.Entities
Imports Cdm.DataCore.LookupTables
Imports Cdm.DataCore.UserSecurity

Partial Class admin_users
    Inherits System.Web.UI.Page

#Region "CONSTANTS"
    Private Const _CLASS_NAME As String = "admin_users"
    Private Const _DEFAULT_DROPDOWNLIST_VALUE As Integer = -1
    Private Const _DEFAULT_DROPDOWNLIST_TEXT As String = ""
#End Region

#Region "PRIVATE MEMBERS"

    Private key As String
    Private role As String
    Private userId As String
    Private country As String
    Private status As String
    Private isError As Boolean

#End Region

#Region "PRIVATE METHODS"

    Private Sub PopulateAgencyDropDownList()

        Try

            Me.PopulateAgencyDropDownList(Me.RoleDropDownList.Value)

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the RoleDropDownList_SelectedIndexChanged() method.", ex)
            Throw (ex)
        End Try

    End Sub

    Private Sub PopulateAgencyDropDownList(ByVal roleId As Integer)

        Try

            Select Case (roleId)
                Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin
                    Me.AgencyDropDownList.DataSource = Entities.FMSA.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
                    Me.AgencyDropDownList.DataTextField = "AgencyName"
                    Me.AgencyDropDownList.DataValueField = "ID"
                    Me.AgencyDropDownList.DataBind()
                Case UserSecurity.Role.RoleType.SupportBroker, UserSecurity.Role.RoleType.SupportBrokerAdmin
                    Me.AgencyDropDownList.DataSource = Entities.SupportBrokerAgency.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
                    Me.AgencyDropDownList.DataTextField = "AgencyName"
                    Me.AgencyDropDownList.DataValueField = "ID"
                    Me.AgencyDropDownList.DataBind()
                Case UserSecurity.Role.RoleType.LocalProgramUser
                    Me.AgencyDropDownList.DataSource = Entities.LocalProgram.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
                    Me.AgencyDropDownList.DataTextField = "LocalProgramName"
                    Me.AgencyDropDownList.DataValueField = "ID"
                    Me.AgencyDropDownList.DataBind()
                Case Else
                    Me.AgencyDropDownList.Items.Clear()
            End Select

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the RoleDropDownList_SelectedIndexChanged(int) method.", ex)
            Throw (ex)
        End Try

    End Sub

    Private Sub BindDropDowns()

        Try

            'Me.RoleDropDownList.DataSource = UserSecurity.Role.ListByCreator(UserAuthorization.CurrentUser.RoleId)
            Me.RoleDropDownList.DataSource = UserSecurity.Role.ListSearchable(UserAuthorization.CurrentUser.RoleId)
            Me.RoleDropDownList.DataBind()

            If Request.QueryString("TYPE") IsNot Nothing Then
                Me.RoleDropDownList.SelectedValue = GetRoleItem(Request.QueryString("TYPE"))
            End If

            Me.PopulateAgencyDropDownList(Me.RoleDropDownList.SelectedValue)

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the BindDropDowns() method.", ex)
            Throw (ex)
        End Try

    End Sub

    Private Function GetRoleItem(ByVal requestValue As String) As String
        Select Case requestValue.ToUpper

            Case "FMSA"
                Return CInt(Cdm.DataCore.UserSecurity.Role.RoleType.FMSA).ToString()
            Case "SUPPORTBROKER"
                Return CInt(Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker).ToString()
            Case Else
                Return ""
        End Select
    End Function


    Private Function ValidateSearchCriteria()

        Try
            If Me.LastNameTextBox.Value.Trim().Length > 0 Or _
                Me.FirstNameTextBox.Value.Trim().Length > 0 Or _
                Me.RoleDropDownList.Value <> _DEFAULT_DROPDOWNLIST_VALUE Then
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the BindDropDowns() method.", ex)
            Throw (ex)
        End Try

    End Function

    Private Sub SetFormPermissons()

        Try

            Dim userID As Integer = UserAuthorization.CurrentUser.UserId
            Dim roleId As Integer = UserAuthorization.CurrentUser.RoleId

            'PRE-SELECT THE ROLE DROPDOWN LIST
            If Request.QueryString("TYPE") Is Nothing Then
                Me.RoleDropDownList.Value = roleId
            End If

            Select Case (roleId)

                Case UserSecurity.Role.RoleType.SysAdmin, _
                     UserSecurity.Role.RoleType.StateAdmin, _
                     UserSecurity.Role.RoleType.StateOffice

                    'DISPLAY AND ENABLE BOTH DROPDOWN LISTS
                    Me.RoleDropDownList.Editable = True

                    Me.ToggleAgencyVisibility(False, True, True)

                Case UserSecurity.Role.RoleType.FMSA

                    Dim oFmsaUser As FMSAUser
                    oFmsaUser = Cdm.DataCore.Entities.FMSAUser.RetrieveByUserId(userID)

                    'DISABLE THE DROPDOWN LISTS
                    If Request.QueryString("TYPE") Is Nothing Then
                        Me.RoleDropDownList.Value = roleId
                    End If
                    Me.RoleDropDownList.Visible = True
                    Me.RoleDropDownList.Editable = False

                    'POPULATE THE AGENCY DROPDOWN LIST
                    Me.PopulateAgencyDropDownList(roleId)
                    Me.AgencyDropDownList.Value = oFmsaUser.FMSAId

                    Me.ToggleAgencyVisibility(True, False, False)

                Case UserSecurity.Role.RoleType.FMSAAdmin

                    'GET THE FMSA OBJECT FOR THIS USER
                    Dim oFmsaUser As FMSAUser
                    oFmsaUser = Cdm.DataCore.Entities.FMSAUser.RetrieveByUserId(userID)

                    'PRE-SELECT THE DROPDOWN VALUE & DISABLE THE DROPDOWN
                    If Request.QueryString("TYPE") Is Nothing Then
                        Me.RoleDropDownList.Value = roleId
                    End If
                    Me.RoleDropDownList.Editable = True

                    'POPULATE THE AGENCY DROPDOWN LIST
                    Me.PopulateAgencyDropDownList(roleId)
                    Me.AgencyDropDownList.Value = oFmsaUser.FMSAId

                    Me.ToggleAgencyVisibility(True, False, True)

                Case UserSecurity.Role.RoleType.SupportBroker

                    Dim oSupportBroker As SupportBroker
                    oSupportBroker = Entities.SupportBroker.RetrieveByUserId(userID)

                    'PRE-SELECT THE DROPDOWN VALUE & DISABLE THE DROPDOWN
                    If Request.QueryString("TYPE") Is Nothing Then
                        Me.RoleDropDownList.Value = roleId
                    End If
                    Me.RoleDropDownList.Editable = False

                    'POPULATE THE AGENCY DROPDOWN LIST
                    Me.PopulateAgencyDropDownList(roleId)
                    Me.AgencyDropDownList.Value = oSupportBroker.SupportBrokerAgencyId

                    Me.ToggleAgencyVisibility(True, False, False)

                Case UserSecurity.Role.RoleType.SupportBrokerAdmin

                    Dim oSupportBrokerAdmin As SupportBroker = Nothing
                    oSupportBrokerAdmin = Entities.SupportBroker.RetrieveByUserId(userID)

                    'PRE-SELECT THE DROPDOWN VALUE & DISABLE THE DROPDOWN
                    If Request.QueryString("TYPE") Is Nothing Then
                        Me.RoleDropDownList.Value = roleId
                    End If
                    Me.RoleDropDownList.Editable = True

                    'POPULATE THE AGENCY DROPDOWN LIST
                    Me.PopulateAgencyDropDownList(roleId)
                    Me.AgencyDropDownList.Value = oSupportBrokerAdmin.SupportBrokerAgencyId

                    Me.ToggleAgencyVisibility(True, False, True)

                Case UserSecurity.Role.RoleType.LocalProgramUser

                    Dim oLocalProgramUser As LocalProgramUser
                    oLocalProgramUser = Entities.LocalProgramUser.RetrieveByUserId(userID)

                    If Request.QueryString("TYPE") Is Nothing Then
                        Me.RoleDropDownList.Value = roleId
                    End If
                    Me.RoleDropDownList.Editable = False

                    'POPULATE THE AGENCY DROPDOWN LIST
                    Me.PopulateAgencyDropDownList(roleId)
                    Me.AgencyDropDownList.Value = oLocalProgramUser.LocalProgramId

                    Me.ToggleAgencyVisibility(True, False, True)

                Case UserSecurity.Role.RoleType.StateOffice

                    Me.RoleDropDownList.Visible = True

                Case Else

                    'SHOULDN'T BE HERE!!!
                    Me.RoleDropDownList.Visible = False
                    Me.ToggleAgencyVisibility(False, False, False)

            End Select

        Catch ex As ApplicationException
            ErrorLog(_CLASS_NAME, "Error in SetFormPermissons() method.", ex)
            Throw ex
        End Try

    End Sub

    Private Sub PopulateMailingAddress(ByVal populateFields As Boolean)

        Try

            Dim txtSA1 As TextBox = Nothing
            Dim txtSA2 As TextBox = Nothing
            Dim txtSA3 As TextBox = Nothing
            Dim txtSACity As TextBox = Nothing
            Dim txtSAState As TextBox = Nothing
            Dim txtSAZip As TextBox = Nothing
            Dim txtMA1 As TextBox = Nothing
            Dim txtMA2 As TextBox = Nothing
            Dim txtMA3 As TextBox = Nothing
            Dim txtMACity As TextBox = Nothing
            Dim txtMAState As TextBox = Nothing
            Dim txtMAZip As TextBox = Nothing

            If SubmitButton.Text = "Save" Then

                txtSA1 = CType(UserFormView.FindControl("txtSA1"), TextBox)
                txtSA2 = CType(UserFormView.FindControl("txtSA2"), TextBox)
                txtSA3 = CType(UserFormView.FindControl("txtSA3"), TextBox)
                txtSACity = CType(UserFormView.FindControl("txtSACity"), TextBox)
                txtSAState = CType(UserFormView.FindControl("txtSAState"), TextBox)
                txtSAZip = CType(UserFormView.FindControl("txtSAZip"), TextBox)

                txtMA1 = CType(UserFormView.FindControl("txtMA1"), TextBox)
                txtMA2 = CType(UserFormView.FindControl("txtMA2"), TextBox)
                txtMA3 = CType(UserFormView.FindControl("txtMA3"), TextBox)
                txtMACity = CType(UserFormView.FindControl("txtMACity"), TextBox)
                txtMAState = CType(UserFormView.FindControl("txtMAState"), TextBox)
                txtMAZip = CType(UserFormView.FindControl("txtMAZip"), TextBox)

            ElseIf Me.SubmitButton.Text = "Update" Then

                txtSA1 = CType(UserFormView.FindControl("editSA1"), TextBox)
                txtSA2 = CType(UserFormView.FindControl("editSA2"), TextBox)
                txtSA3 = CType(UserFormView.FindControl("editSA3"), TextBox)
                txtSACity = CType(UserFormView.FindControl("editSACity"), TextBox)
                txtSAState = CType(UserFormView.FindControl("editSAState"), TextBox)
                txtSAZip = CType(UserFormView.FindControl("editSAZip"), TextBox)

                txtMA1 = CType(UserFormView.FindControl("editMA1"), TextBox)
                txtMA2 = CType(UserFormView.FindControl("editMA2"), TextBox)
                txtMA3 = CType(UserFormView.FindControl("editMA3"), TextBox)
                txtMACity = CType(UserFormView.FindControl("editMACity"), TextBox)
                txtMAState = CType(UserFormView.FindControl("editMAState"), TextBox)
                txtMAZip = CType(UserFormView.FindControl("editMAZip"), TextBox)

            End If

            If populateFields Then
                txtMA1.Text = txtSA1.Text
                txtMA2.Text = txtSA2.Text
                txtMA3.Text = txtSA3.Text
                txtMACity.Text = txtSACity.Text
                txtMAState.Text = txtSAState.Text
                txtMAZip.Text = txtSAZip.Text
            Else
                txtMA1.Text = ""
                txtMA2.Text = ""
                txtMA3.Text = ""
                txtMACity.Text = ""
                txtMAState.Text = ""
                txtMAZip.Text = ""
            End If

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "Error in PopulateMailingAddress().", ex)
            Throw ex
        End Try

    End Sub

    Private Function VerifyRoleChange() As Boolean

        Try
            Me.panelChangeRoleVerification.Visible = True
            Me.SubmitButton.Enabled = False
            Me.CancelButton.Enabled = False
        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the VerifyRoleChange() method.", ex)
            Throw ex
        End Try

    End Function

    Private Function GetUserAgencyProgram(ByVal userId As Integer, _
                                          ByVal roleId As Integer) _
                                          As Integer

        Try

            Select Case roleId
                Case Cdm.DataCore.UserSecurity.Role.RoleType.FMSA, Cdm.DataCore.UserSecurity.Role.RoleType.FMSAAdmin
                    Dim oFMSA As FMSAUser = FMSAUser.RetrieveByUserId(userId)
                    Return oFMSA.FMSAId
                Case Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker, Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin
                    Dim oSupportBroker As SupportBroker = SupportBroker.RetrieveByUserId(userId)
                    Return oSupportBroker.SupportBrokerAgencyId
                Case Cdm.DataCore.UserSecurity.Role.RoleType.LocalProgramUser
                    Dim oLocalProgram As LocalProgramUser = LocalProgramUser.RetrieveByUserId(userId)
                    Return oLocalProgram.LocalProgramId
            End Select

        Catch ex As Exception
            Return 0
        End Try

    End Function

    Private Sub ToggleAgencyVisibility(ByVal isVisible As Boolean, _
                                       ByVal isEditable As Boolean, _
                                       ByVal isAdmin As Boolean)

        Try

            Me.AgencyDropDownList.Visible = isVisible

            Me.AgencyDropDownList.Editable = isEditable

            Me.AddButton.Visible = isAdmin

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the ToggleAgencyVisibility(bool) method.", ex)
            Throw ex
        End Try

    End Sub

    Protected Sub formError(ByVal strError As String)
        ErrorSummary.Text = strError
        ErrorSummary.Visible = True
    End Sub

    Protected Function validateUserId(ByVal logonId As String, _
                                      ByVal userid As Integer) _
                                      As Boolean

        isError = Cdm.DataCore.UserSecurity.CDMUser.OtherUserExists(logonId, userid)
        Return isError

    End Function

    Private Function ValidateForm(ByVal userId As Integer) As Boolean

        Try
            Dim sErrorText As String = String.Empty
            Dim txtFName As TextBox = CType(UserFormView.FindControl("txtFName"), TextBox)
            Dim txtLName As TextBox = CType(UserFormView.FindControl("txtLName"), TextBox)
            Dim txtSA1 As TextBox = CType(UserFormView.FindControl("txtSA1"), TextBox)
            Dim txtSACity As TextBox = CType(UserFormView.FindControl("txtSACity"), TextBox)
            Dim txtSAState As TextBox = CType(UserFormView.FindControl("txtSAState"), TextBox)
            Dim txtSAZip As TextBox = CType(UserFormView.FindControl("txtSAZip"), TextBox)
            Dim txtLogon As TextBox = CType(UserFormView.FindControl("txtLogon"), TextBox)
            Dim cbxUseAgencyAddress As CheckBox = CType(UserFormView.FindControl("CheckBoxAgencyAddress"), CheckBox)
            Dim cbxUseMailingAddress As CheckBox = CType(UserFormView.FindControl("CheckBoxMailingAddress"), CheckBox)
            Dim ddlRole As DropDownList = CType(UserFormView.FindControl("ddlRole"), DropDownList)

            If Me.SubmitButton.Text.ToUpper() = "SAVE" Then
                ddlRole = CType(UserFormView.FindControl("ddlRole"), DropDownList)
                cbxUseAgencyAddress = CType(UserFormView.FindControl("CheckBoxAgencyAddress"), CheckBox)
                cbxUseMailingAddress = CType(UserFormView.FindControl("CheckBoxMailingAddress"), CheckBox)
                txtFName = CType(UserFormView.FindControl("txtFName"), TextBox)
                txtLName = CType(UserFormView.FindControl("txtLName"), TextBox)
                txtSA1 = CType(UserFormView.FindControl("txtSA1"), TextBox)
                txtSACity = CType(UserFormView.FindControl("txtSACity"), TextBox)
                txtSAState = CType(UserFormView.FindControl("txtSAState"), TextBox)
                txtSAZip = CType(UserFormView.FindControl("txtSAZip"), TextBox)
                txtLogon = CType(UserFormView.FindControl("txtLogon"), TextBox)
            ElseIf Me.SubmitButton.Text.ToUpper() = "UPDATE" Then
                ddlRole = CType(UserFormView.FindControl("ddleditRole"), DropDownList)
                cbxUseAgencyAddress = CType(UserFormView.FindControl("CheckBoxEditAgencyAddress"), CheckBox)
                cbxUseMailingAddress = CType(UserFormView.FindControl("CheckBoxEditMailingAddress"), CheckBox)
                txtFName = CType(UserFormView.FindControl("editFName"), TextBox)
                txtLName = CType(UserFormView.FindControl("editLName"), TextBox)
                txtSA1 = CType(UserFormView.FindControl("editSA1"), TextBox)
                txtSACity = CType(UserFormView.FindControl("editSACity"), TextBox)
                txtSAState = CType(UserFormView.FindControl("editSAState"), TextBox)
                txtSAZip = CType(UserFormView.FindControl("editSAZip"), TextBox)
                txtLogon = CType(UserFormView.FindControl("editLogon"), TextBox)
            End If

            Me.hfUseAgencyAddress.Value = cbxUseAgencyAddress.Checked
            Me.hfUseAsMailingAddress.Value = cbxUseMailingAddress.Checked

            'CHECK THE USER'S ROLE FIRST
            If (ddlRole.SelectedValue = UserSecurity.Role.RoleType.FMSA Or _
                ddlRole.SelectedValue = UserSecurity.Role.RoleType.FMSAAdmin Or _
                ddlRole.SelectedValue = UserSecurity.Role.RoleType.SupportBroker Or _
                ddlRole.SelectedValue = UserSecurity.Role.RoleType.SupportBrokerAdmin) Then

                If txtFName.Text = "" Or txtLName.Text = "" Or txtLogon.Text = "" Or _
                    (cbxUseAgencyAddress.Checked = False And (txtSA1.Text = "" Or txtSACity.Text = "" Or txtSAState.Text = "" Or txtSAZip.Text = "")) Then

                    sErrorText = "Fields marked with an asterisk(*) need to be filled in.<br /> The following field(s) require input:<br />"

                    If txtFName.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " First Name" & ","
                    End If

                    If txtLName.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " Last Name" & ","
                    End If

                    If cbxUseAgencyAddress.Checked = False And (txtSA1.Text = "" Or txtSACity.Text = "" Or txtSAState.Text = "" Or txtSAZip.Text = "") Then
                        If txtSA1.Text.Trim().Length <= 0 Then
                            sErrorText = sErrorText & " Street Address 1" & ","
                        End If

                        If txtSACity.Text.Trim().Length <= 0 Then
                            sErrorText = sErrorText & " City" & ","
                        End If

                        If txtSAState.Text.Trim().Length <= 0 Then
                            sErrorText = sErrorText & " State" & ","
                        End If

                        If txtSAZip.Text.Trim().Length <= 0 Then
                            sErrorText = sErrorText & " Zip Code" & ","
                        End If
                    End If

                    If txtLogon.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " Logon ID" & ","
                    End If

                    formError(sErrorText.Remove(sErrorText.LastIndexOf(",")))
                    Return False
                    Exit Function

                End If
            Else

                If txtFName.Text = "" Or txtLName.Text = "" Or txtLogon.Text = "" Or txtSA1.Text = "" Or txtSACity.Text = "" Or txtSAState.Text = "" Or txtSAZip.Text = "" Then

                    sErrorText = "Fields marked with an asterisk(*) need to be filled in.<br /> The following fields require input:<br />"

                    If txtFName.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " First Name" & ","
                    End If

                    If txtLName.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " Last Name" & ","
                    End If

                    If txtSA1.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " Street Address 1" & ","
                    End If

                    If txtSACity.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " City" & ","
                    End If

                    If txtSAState.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " State" & ","
                    End If

                    If txtSAZip.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " Zip Code" & ","
                    End If

                    If txtLogon.Text.Trim().Length <= 0 Then
                        sErrorText = sErrorText & " Logon ID" & ","
                    End If

                    formError(sErrorText.Remove(sErrorText.LastIndexOf(",")))
                    Return False
                    Exit Function

                End If

            End If

            'VALIDATE THE LOGIN ID
            If Not txtLogon Is Nothing Then

                isError = Me.validateUserId(txtLogon.Text, userId)

                If isError Then
                    sErrorText = "User logon already exists. Please enter a different value and resubmit the form."
                    formError(sErrorText)
                    Return False
                    Exit Function
                End If

            End If

            Me.ErrorSummary.Visible = False
            Return True

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the ValidateForm() method.", ex)
            Throw ex
        End Try

    End Function

    Private Sub AssignAgencyAddress(ByVal roleId As Integer, ByVal agencyId As Integer, ByVal userId As Integer, ByVal useAsMailingAddress As Boolean)
        Try
            Dim user As CDMUser

            Select Case roleId
                Case Cdm.DataCore.UserSecurity.Role.RoleType.FMSA, Cdm.DataCore.UserSecurity.Role.RoleType.FMSAAdmin

                    user = CDMUser.Retrieve(userId)

                    Dim fmsaAgency As FMSA
                    fmsaAgency = FMSA.Retrieve(agencyId)

                    user.StreetAddress1 = fmsaAgency.Address1
                    user.StreetAddress2 = fmsaAgency.Address2
                    user.StreetAddress3 = fmsaAgency.Address3
                    user.StreetAddressCity = fmsaAgency.City
                    user.StreetAddressState = fmsaAgency.State
                    user.StreetAddressZip = fmsaAgency.Zip

                    If useAsMailingAddress Then
                        user.MailingAddress1 = fmsaAgency.Address1
                        user.MailingAddress2 = fmsaAgency.Address2
                        user.MailingAddress3 = fmsaAgency.Address3
                        user.MailingAddressCity = fmsaAgency.City
                        user.MailingAddressState = fmsaAgency.State
                        user.MailingAddressZip = fmsaAgency.Zip
                    End If

                    user.Persist()

                Case Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker, Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin

                    user = CDMUser.Retrieve(userId)

                    Dim sbAgency As SupportBrokerAgency
                    sbAgency = SupportBrokerAgency.Retrieve(agencyId)

                    user.StreetAddress1 = sbAgency.Address1
                    user.StreetAddress2 = sbAgency.Address2
                    user.StreetAddress3 = sbAgency.Address3
                    user.StreetAddressCity = sbAgency.City
                    user.StreetAddressState = sbAgency.State
                    user.StreetAddressZip = sbAgency.Zip

                    If useAsMailingAddress Then
                        user.MailingAddress1 = sbAgency.Address1
                        user.MailingAddress2 = sbAgency.Address2
                        user.MailingAddress3 = sbAgency.Address3
                        user.MailingAddressCity = sbAgency.City
                        user.MailingAddressState = sbAgency.State
                        user.MailingAddressZip = sbAgency.Zip
                    End If

                    user.Persist()

            End Select

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the AssignAgencyAddress() method.", ex)

            Throw ex
        End Try
    End Sub

#End Region

#Region "PUBLIC METHODS"

    Public Function RoleIDList() As System.Collections.Generic.List(Of Cdm.DataCore.UserSecurity.Role)
        Return Cdm.DataCore.UserSecurity.Role.ListAll(_DEFAULT_DROPDOWNLIST_VALUE, _DEFAULT_DROPDOWNLIST_TEXT)
    End Function

    Public Function DisplayRole(ByVal roleID As Integer) As String
        Dim i As Integer
        For i = 0 To RoleIDList().Count - 1
            If RoleIDList(i).RoleId = roleID Then
                Return RoleIDList(i).RoleDisplayName
                'Return RoleIDList(i).RoleName
            End If
        Next
        Return ""
    End Function

    Public Function RoleList() As List(Of Cdm.DataCore.UserSecurity.Role)
        If role = Cdm.DataCore.UserSecurity.Role.RoleType.Participant Or _
        role = Cdm.DataCore.UserSecurity.Role.RoleType.Representative Or _
        role = Cdm.DataCore.UserSecurity.Role.RoleType.LegalGuardian Then
            Return Cdm.DataCore.UserSecurity.Role.ListAll()
        Else
            Return Cdm.DataCore.UserSecurity.Role.ListSpecial()
        End If
    End Function

    Public Function RoleEditable() As Boolean

        If role = Cdm.DataCore.UserSecurity.Role.RoleType.Participant Or _
            role = Cdm.DataCore.UserSecurity.Role.RoleType.Representative Or _
            role = Cdm.DataCore.UserSecurity.Role.RoleType.LegalGuardian Then
            Return False
        Else

            If (role = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker Or role = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin) Then
                If Cdm.DataCore.CaseNotes.SupportBrokerCasesDisplay.ListByUser(Session("CurrentUserId"), "LastName", False).Count > 0 Then
                    Return False
                Else
                    Return True
                End If
            Else
                Return True
            End If

        End If
    End Function

#End Region

#Region "EVENT HANDLERS"

    Protected Sub AddButton_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles AddButton.Click

        'Me.LabelHeader.Text = "Add a new user"
        Me.FindUserPanel.Visible = False
        SubmitButton.Text = "Save"
        SubmitButton.Visible = True
        CancelButton.Visible = True
        lblRequired.Visible = True

        Me.UserFormView.ChangeMode(FormViewMode.Insert)
        Me.UserFormView.Visible = True
        Me.AddEditUserPanel.Visible = True

        Dim ddlRole As DropDownList = Nothing
        ddlRole = CType(UserFormView.FindControl("ddlRole"), DropDownList)

        If Not ddlRole Is Nothing Then
            'POPULATE THE ROLE DROPDOWN LIST BASED ON THE ROLE OF THE CURRENT USER
            ddlRole.DataSource = UserSecurity.Role.ListByCreator(UserAuthorization.CurrentUser.RoleId)
            ddlRole.DataBind()
            ddlRole.Attributes.Add("onchange", "javascript: SetUploadHiddenField('" & ddlRole.ClientID & "', '" & Me.UploadHiddenField.ClientID & "');")
        End If

    End Sub



    Protected Sub CancelButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles CancelButton.Click

        'Me.LabelHeader.Text = "Add a user or search for users by name or role."
        UserFormView.Visible = False
        Me.AddEditUserPanel.Visible = False
        SubmitButton.Visible = False
        CancelButton.Visible = False
        lblRequired.Visible = False
        Me.FindUserPanel.Visible = True
        SetStatus("Action Cancelled.")

    End Sub

    Protected Sub SubmitButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles SubmitButton.Click

        Dim roleChanged As Boolean = False
        Dim intAgencyDefaultValue As Integer = 0
        Dim sErrorText As String = String.Empty

        If SubmitButton.Text = "Save" Then

            roleChanged = True

            Dim newUser As Cdm.DataCore.UserSecurity.CDMUser = New Cdm.DataCore.UserSecurity.CDMUser()

            Dim txtFName As TextBox = CType(UserFormView.FindControl("txtFName"), TextBox)
            Dim txtMName As TextBox = CType(UserFormView.FindControl("txtMName"), TextBox)
            Dim txtLName As TextBox = CType(UserFormView.FindControl("txtLName"), TextBox)

            Dim txtSA1 As TextBox = CType(UserFormView.FindControl("txtSA1"), TextBox)
            Dim txtSA2 As TextBox = CType(UserFormView.FindControl("txtSA2"), TextBox)
            Dim txtSA3 As TextBox = CType(UserFormView.FindControl("txtSA3"), TextBox)
            Dim txtSACity As TextBox = CType(UserFormView.FindControl("txtSACity"), TextBox)
            Dim txtSAState As TextBox = CType(UserFormView.FindControl("txtSAState"), TextBox)
            Dim txtSAZip As TextBox = CType(UserFormView.FindControl("txtSAZip"), TextBox)
            Dim ddlCounty As DropDownList = CType(UserFormView.FindControl("ddlCounty"), DropDownList)

            Dim txtLogon As TextBox = CType(UserFormView.FindControl("txtLogon"), TextBox)
            Dim txtPassword As TextBox = CType(UserFormView.FindControl("txtPassword"), TextBox)

            Dim ddlStatus As DropDownList = CType(UserFormView.FindControl("ddlStatus"), DropDownList)
            Dim ddlRole As DropDownList = CType(UserFormView.FindControl("ddlRole"), DropDownList)

            If Not Me.ValidateForm(0) Then
                Exit Sub
            End If

            Dim txtMA1 As TextBox = CType(UserFormView.FindControl("txtMA1"), TextBox)
            Dim txtMA2 As TextBox = CType(UserFormView.FindControl("txtMA2"), TextBox)
            Dim txtMA3 As TextBox = CType(UserFormView.FindControl("txtMA3"), TextBox)
            Dim txtMACity As TextBox = CType(UserFormView.FindControl("txtMACity"), TextBox)
            Dim txtMAState As TextBox = CType(UserFormView.FindControl("txtMAState"), TextBox)
            Dim txtMAZip As TextBox = CType(UserFormView.FindControl("txtMAZip"), TextBox)

            Dim inputPhone As InputControls.PhoneInputControl = CType(UserFormView.FindControl("InputTelephoneNumber"), InputControls.PhoneInputControl)
            Dim inputFax As InputControls.PhoneInputControl = CType(UserFormView.FindControl("InputFaxNumber"), InputControls.PhoneInputControl)

            Dim txtEmail As TextBox = CType(UserFormView.FindControl("txtEmail"), TextBox)

            newUser.FirstName = txtFName.Text
            newUser.MiddleName = txtMName.Text
            newUser.LastName = txtLName.Text

            If Me.hfUseAgencyAddress.Value.ToUpper() = "FALSE" Then
                newUser.StreetAddress1 = txtSA1.Text
                newUser.StreetAddress2 = txtSA2.Text
                newUser.StreetAddress3 = txtSA3.Text
                newUser.StreetAddressCity = txtSACity.Text
                newUser.StreetAddressState = txtSAState.Text
                newUser.StreetAddressZip = txtSAZip.Text

                newUser.MailingAddress1 = txtMA1.Text
                newUser.MailingAddress2 = txtMA2.Text
                newUser.MailingAddress3 = txtMA3.Text
                newUser.MailingAddressCity = txtMACity.Text
                newUser.MailingAddressState = txtMAState.Text
                newUser.MailingAddressZip = txtMAZip.Text
            End If

            newUser.CountyId = ddlCounty.SelectedValue
            newUser.PhoneNumber = inputPhone.Value
            newUser.FaxNumber = inputFax.Value
            newUser.EmailAddress = txtEmail.Text
            newUser.LogonId = txtLogon.Text
            newUser.Password = txtPassword.Text
            newUser.Status = ddlStatus.SelectedValue
            newUser.RoleId = ddlRole.SelectedValue
            newUser.ApplicationHomePage = EntityController.ApplicationHomePage
            newUser.LastModified = UserAuthorization.CurrentUser.LogonId
            newUser.DateModified = Now
            newUser.Persist()
            CreateSupportObject(newUser)

            userId = newUser.UserId
            role = ddlRole.SelectedValue

            Me.hfUserId.Value = userId
            Me.hfRole.Value = role
            SetStatus("New user created.")
        ElseIf SubmitButton.Text = "Update" Then

            Dim dKey As DataKey = UserFormView.DataKey
            Dim newUser As List(Of Cdm.DataCore.UserSecurity.CDMUser)

            key = dKey.Value
            newUser = Cdm.DataCore.UserSecurity.CDMUser.ListByUserID(key)

            Dim txtFName As TextBox = CType(UserFormView.FindControl("editFName"), TextBox)
            Dim txtMName As TextBox = CType(UserFormView.FindControl("editMName"), TextBox)
            Dim txtLName As TextBox = CType(UserFormView.FindControl("editLName"), TextBox)

            Dim txtSA1 As TextBox = CType(UserFormView.FindControl("editSA1"), TextBox)
            Dim txtSA2 As TextBox = CType(UserFormView.FindControl("editSA2"), TextBox)
            Dim txtSA3 As TextBox = CType(UserFormView.FindControl("editSA3"), TextBox)
            Dim txtSACity As TextBox = CType(UserFormView.FindControl("editSACity"), TextBox)
            Dim txtSAState As TextBox = CType(UserFormView.FindControl("editSAState"), TextBox)
            Dim txtSAZip As TextBox = CType(UserFormView.FindControl("editSAZip"), TextBox)
            Dim ddlCounty As DropDownList = CType(UserFormView.FindControl("ddleditCounty"), DropDownList)

            If Not Me.ValidateForm(CType(key, Integer)) Then
                Exit Sub
            End If

            Dim txtMA1 As TextBox = CType(UserFormView.FindControl("editMA1"), TextBox)
            Dim txtMA2 As TextBox = CType(UserFormView.FindControl("editMA2"), TextBox)
            Dim txtMA3 As TextBox = CType(UserFormView.FindControl("editMA3"), TextBox)
            Dim txtMACity As TextBox = CType(UserFormView.FindControl("editMACity"), TextBox)
            Dim txtMAState As TextBox = CType(UserFormView.FindControl("editMAState"), TextBox)
            Dim txtMAZip As TextBox = CType(UserFormView.FindControl("editMAZip"), TextBox)

            Dim inputPhone As InputControls.PhoneInputControl = CType(UserFormView.FindControl("InputEditTelephoneNumber"), InputControls.PhoneInputControl)
            Dim inputFax As InputControls.PhoneInputControl = CType(UserFormView.FindControl("InputEditFaxNumber"), InputControls.PhoneInputControl)

            Dim txtEmail As TextBox = CType(UserFormView.FindControl("editEmail"), TextBox)

            Dim txtLogon As TextBox = CType(UserFormView.FindControl("editLogon"), TextBox)
            Dim txtPassword As TextBox = CType(UserFormView.FindControl("editPassword"), TextBox)

            Dim ddlStatus As DropDownList = CType(UserFormView.FindControl("ddleditStatus"), DropDownList)
            Dim ddlRole As DropDownList = CType(UserFormView.FindControl("ddleditRole"), DropDownList)

            'CHECK IF THE ROLE HAS CHANGED
            If newUser(0).RoleId = CType(ddlRole.SelectedValue, Integer) Then
                roleChanged = False
            Else
                roleChanged = True
                If Me.hfRoleChangeVerified.Value.ToUpper = "FALSE" Then
                    If Not Me.VerifyRoleChange() Then
                        Exit Sub
                    End If
                End If
            End If

            newUser(0).UserId = key
            newUser(0).FirstName = txtFName.Text
            newUser(0).MiddleName = txtMName.Text
            newUser(0).LastName = txtLName.Text

            If Me.hfUseAgencyAddress.Value.ToUpper() = "FALSE" Then
                newUser(0).StreetAddress1 = txtSA1.Text
                newUser(0).StreetAddress2 = txtSA2.Text
                newUser(0).StreetAddress3 = txtSA3.Text
                newUser(0).StreetAddressCity = txtSACity.Text
                newUser(0).StreetAddressState = txtSAState.Text
                newUser(0).StreetAddressZip = txtSAZip.Text

                newUser(0).MailingAddress1 = txtMA1.Text
                newUser(0).MailingAddress2 = txtMA2.Text
                newUser(0).MailingAddress3 = txtMA3.Text
                newUser(0).MailingAddressCity = txtMACity.Text
                newUser(0).MailingAddressState = txtMAState.Text
                newUser(0).MailingAddressZip = txtMAZip.Text
            End If

            newUser(0).CountyId = ddlCounty.SelectedValue
            newUser(0).PhoneNumber = inputPhone.Value
            newUser(0).FaxNumber = inputFax.Value
            newUser(0).EmailAddress = txtEmail.Text
            If newUser(0).LogonId <> txtLogon.Text Then
                isError = validateUserId(txtLogon.Text, newUser(0).UserId)
                If isError Then
                    formError("User logon already exists. Please enter a different value and resubmit the form.")
                    Exit Sub
                End If
            End If
            newUser(0).LogonId = txtLogon.Text
            newUser(0).Password = txtPassword.Text
            newUser(0).Status = ddlStatus.SelectedValue
            newUser(0).RoleId = ddlRole.SelectedValue
            newUser(0).LastModified = UserAuthorization.CurrentUser.LogonId
            newUser(0).DateModified = Now
            Try
                newUser(0).Persist()
                SetStatus(String.Concat("User Information updated for ", txtLogon.Text))
            Catch ex As Exception
                If ex.InnerException IsNot Nothing Then
                    If Not String.IsNullOrEmpty(ex.InnerException.Message) Then
                        formError(ex.InnerException.Message)
                        Exit Sub
                    End If
                End If
                formError(ex.Message)
                Exit Sub
            End Try

            userId = newUser(0).UserId
            role = ddlRole.SelectedValue

            If roleChanged Then
                intAgencyDefaultValue = 0
            Else
                intAgencyDefaultValue = Me.GetUserAgencyProgram(userId, role)
            End If

            Me.hfUserId.Value = userId
            Me.hfRole.Value = role

        End If

        SubmitButton.Visible = False
        CancelButton.Visible = False
        UserFormView.Visible = False
        AddEditUserPanel.Visible = False
        lblRequired.Visible = False

        'CLEAR THE DROPDOWN LIST 
        Dim ddlAgency As DropDownList = CType(Me.pnlAgency.FindControl("ddlAgency"), DropDownList)
        ddlAgency.Items.Clear()

        Me.UploadPanel.Visible = False

        Select Case CType(role, Role.RoleType)
            Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin, _
             UserSecurity.Role.RoleType.LocalProgramUser, UserSecurity.Role.RoleType.SupportBroker, UserSecurity.Role.RoleType.SupportBrokerAdmin

                If UserAuthorization.HasUpdatePermission(Permission.PermissionType.Admin) Then
                    PopulateAgenciesForAdminUser(role, intAgencyDefaultValue)
                Else
                    PopulateAgenciesForAgentUser()
                End If

            Case Else

                Me.UsersObjectDataSource.Select()
                UsersScrollingGridView.DataBind()

                Me.FindUserPanel.Visible = True
                Me.UsersScrollingGridView.Visible = False
                ' Response.Redirect("users.aspx?msg=" & Me.SubmitButton.Text, True)


        End Select

    End Sub

    Private Sub PopulateAgenciesForAgentUser()
        Dim btnAssign As Button = CType(Me.pnlAgency.FindControl("btnAssign"), Button)
        AddHandler btnAssign.Click, AddressOf btnAssign_Click
        Me.ddlAgency.Items.Clear()
        Dim currentRole As Role.RoleType = CType(UserAuthorization.CurrentUser.RoleId, Role.RoleType)
        Select Case currentRole
            Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin
                Dim currentFMSAUser As Cdm.DataCore.Entities.FMSAUser = Cdm.DataCore.Entities.FMSAUser.RetrieveByUserId(UserAuthorization.CurrentUser.UserId)
                If currentFMSAUser.FMSAId > 0 Then
                    Dim FMSAAgency As Cdm.DataCore.Entities.FMSA = Cdm.DataCore.Entities.FMSA.Retrieve(currentFMSAUser.FMSAId)
                    Me.ddlAgency.Items.Add(New ListItem(FMSAAgency.AgencyName, FMSAAgency.FMSAId))
                End If
                lblAssign.Text = "Assign Agency:"
            Case UserSecurity.Role.RoleType.SupportBroker, UserSecurity.Role.RoleType.SupportBrokerAdmin
                Dim currentSBUser As Cdm.DataCore.Entities.SupportBroker = Cdm.DataCore.Entities.SupportBroker.RetrieveByUserId(UserAuthorization.CurrentUser.UserId)
                If currentSBUser.SupportBrokerAgencyId > 0 Then
                    Dim sbAgency As Cdm.DataCore.Entities.SupportBrokerAgency = Cdm.DataCore.Entities.SupportBrokerAgency.Retrieve(currentSBUser.SupportBrokerAgencyId)
                    Me.ddlAgency.Items.Add(New ListItem(sbAgency.AgencyName, sbAgency.SupportBrokerAgencyId))
                End If
                lblAssign.Text = "Assign Agency:"
                Me.UploadPanel.Visible = True
            Case UserSecurity.Role.RoleType.LocalProgramUser
                Dim currentLPUser As Cdm.DataCore.Entities.LocalProgramUser = Cdm.DataCore.Entities.LocalProgramUser.RetrieveByUserId(UserAuthorization.CurrentUser.UserId)
                If currentLPUser.LocalProgramId > 0 Then
                    Dim localProgramOffice As Cdm.DataCore.Entities.LocalProgram = Cdm.DataCore.Entities.LocalProgram.Retrieve(currentLPUser.LocalProgramId)
                    Me.ddlAgency.Items.Add(New ListItem(localProgramOffice.LocalProgramName, localProgramOffice.LocalProgramId))
                End If
                lblAssign.Text = "Assign Local Program:"
        End Select


        pnlAgency.Visible = True
        Me.ddlAgency.Enabled = False


    End Sub

    Private Sub PopulateAgenciesForAdminUser(ByVal role As Role.RoleType, ByVal intAgencyDefaultValue As String)
        If role = Cdm.DataCore.UserSecurity.Role.RoleType.FMSAAdmin Or _
           role = Cdm.DataCore.UserSecurity.Role.RoleType.FMSA Then


            Dim btnAssign As Button = CType(Me.pnlAgency.FindControl("btnAssign"), Button)
            AddHandler btnAssign.Click, AddressOf btnAssign_Click

            Me.odsFMSA.Select()
            ddlAgency.DataSourceID = "odsFMSA"
            ddlAgency.DataValueField = "FMSAId"
            ddlAgency.DataTextField = "AgencyName"
            ddlAgency.AppendDataBoundItems = True
            ddlAgency.Items.Insert(0, "Please Select...")

            If Me.hfUseAgencyAddress.Value.ToUpper = "FALSE" Then
                ddlAgency.Items.Insert(1, "None")
                ddlAgency.Items.Item(1).Value = "0"

                ddlAgency.DataBind()
                ddlAgency.SelectedValue = intAgencyDefaultValue
            Else
                ddlAgency.DataBind()
            End If

            lblAssign.Text = "Assign Agency:"

            pnlAgency.Visible = True

        ElseIf role = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker Then

            Dim btnAssign As Button = CType(Me.pnlAgency.FindControl("btnAssign"), Button)
            AddHandler btnAssign.Click, AddressOf btnAssign_Click

            Me.odsSBA.Select()
            ddlAgency.DataSourceID = "odsSBA"
            ddlAgency.DataTextField = "AgencyName"
            ddlAgency.DataValueField = "SupportBrokerAgencyID"
            ddlAgency.AppendDataBoundItems = True
            ddlAgency.Items.Insert(0, "Please Select...")

            If Me.hfUseAgencyAddress.Value.ToUpper = "FALSE" Then
                ddlAgency.Items.Insert(1, "None")
                ddlAgency.Items.Item(1).Value = "0"

                ddlAgency.DataBind()
                ddlAgency.SelectedValue = intAgencyDefaultValue
            Else
                ddlAgency.DataBind()
            End If

            lblAssign.Text = "Assign Agency:"

            pnlAgency.Visible = True

            Me.UploadPanel.Visible = True

        ElseIf role = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin Then

            Dim btnAssign As Button = CType(Me.pnlAgency.FindControl("btnAssign"), Button)
            AddHandler btnAssign.Click, AddressOf btnAssign_Click

            Me.odsSBA.Select()
            ddlAgency.DataSourceID = "odsSBA"
            ddlAgency.DataTextField = "AgencyName"
            ddlAgency.DataValueField = "SupportBrokerAgencyID"
            ddlAgency.AppendDataBoundItems = True
            ddlAgency.Items.Insert(0, "Please Select...")

            If Me.hfUseAgencyAddress.Value.ToUpper = "FALSE" Then
                ddlAgency.Items.Insert(1, "None")
                ddlAgency.Items.Item(1).Value = "0"

                ddlAgency.DataBind()
                ddlAgency.SelectedValue = intAgencyDefaultValue
            Else
                ddlAgency.DataBind()
            End If

            If intAgencyDefaultValue = 0 Then
                Dim oSBA As SupportBroker
                Try
                    oSBA = SupportBroker.RetrieveByUserId(userId)
                Catch ex As Exception
                    oSBA = Nothing
                End Try

                Me.txtProvider.Visible = True
                Me.lblProvider.Visible = True

                If oSBA IsNot Nothing Then
                    Me.txtProvider.Text = oSBA.MedicaidNumber.ToString()
                End If

            End If

            lblAssign.Text = "Assign Agency:"

            pnlAgency.Visible = True

            Me.UploadPanel.Visible = True

        ElseIf role = Cdm.DataCore.UserSecurity.Role.RoleType.LocalProgramUser Then

            Dim btnAssign As Button = CType(Me.pnlAgency.FindControl("btnAssign"), Button)
            AddHandler btnAssign.Click, AddressOf btnAssign_Click

            Me.odsLocal.Select()
            ddlAgency.DataSourceID = "odsLocal"
            ddlAgency.DataTextField = "LocalProgramName"
            ddlAgency.DataValueField = "LocalProgramID"
            ddlAgency.AppendDataBoundItems = True
            ddlAgency.Items.Insert(0, "Please Select...")
            ddlAgency.Items.Insert(1, "None")
            ddlAgency.Items.Item(1).Value = "0"

            ddlAgency.DataBind()
            ddlAgency.SelectedValue = intAgencyDefaultValue

            lblAssign.Text = "Assign Local Program:"

            pnlAgency.Visible = True
        End If
    End Sub


    ''' <summary>
    ''' For FMSA or FMSA Agents, SBA or Support Brokers, create the
    ''' SupportBroker or FMSA Object as soon as the user is created
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub CreateSupportObject(ByVal newUser As Cdm.DataCore.UserSecurity.CDMUser)
        Dim userRoleType As UserSecurity.Role.RoleType = CType(newUser.RoleId, Role.RoleType)
        Select Case userRoleType
            Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin
                Dim newFMSA As New FMSAUser
                newFMSA.UserId = newUser.UserId
                newFMSA.LastModified = UserAuthorization.CurrentUser.LogonId
                newFMSA.DateModified = Now
                newFMSA.Persist()
            Case UserSecurity.Role.RoleType.SupportBroker, UserSecurity.Role.RoleType.SupportBrokerAdmin
                Dim newSupportBroker As New SupportBroker
                newSupportBroker.UserId = newUser.UserId
                newSupportBroker.LastModified = UserAuthorization.CurrentUser.LogonId
                newSupportBroker.DateModified = Now
                newSupportBroker.Persist()
        End Select

        If CType(newUser.RoleId, Cdm.DataCore.UserSecurity.Role.RoleType) = UserSecurity.Role.RoleType.FMSA Or _
CType(newUser.RoleId, Cdm.DataCore.UserSecurity.Role.RoleType) = UserSecurity.Role.RoleType.FMSAAdmin Then

        End If

    End Sub

    Protected Sub UserFormView_ItemCreated(ByVal sender As Object, _
                                        ByVal e As System.EventArgs) _
                                        Handles UserFormView.ItemCreated

        Dim ddlCounty As DropDownList = CType(UserFormView.FindControl("ddlCounty"), DropDownList)
        Dim roleId As Integer = -1

        If Not ddlCounty Is Nothing Then
            Me.CountiesObjectDataSource.Select()
            ddlCounty.DataSourceID = "odsCounties"
            ddlCounty.DataTextField = "Description"
            ddlCounty.DataValueField = "CountyId"
            ddlCounty.AppendDataBoundItems = True
            ddlCounty.Items.Insert(0, "Please Select...")
            ddlCounty.Items(0).Value = "0"
        End If

        If key <> "" Then
            Dim ddleditStatus As DropDownList = CType(UserFormView.FindControl("ddleditStatus"), DropDownList)
            Dim ddleditCounty As DropDownList = CType(UserFormView.FindControl("ddleditCounty"), DropDownList)

            Dim objUser As Cdm.DataCore.UserSecurity.CDMUser = Cdm.DataCore.UserSecurity.CDMUser.Retrieve(Convert.ToInt32(key))

            roleId = objUser.RoleId

            If Not ddleditCounty Is Nothing Then
                Me.CountiesObjectDataSource.Select()
                ddleditCounty.DataSourceID = "odsCounties"
                ddleditCounty.DataTextField = "Description"
                ddleditCounty.DataValueField = "CountyId"
                ddleditCounty.AppendDataBoundItems = True
                ddleditCounty.Items.Insert(0, "Please Select...")
                ddleditCounty.Items(0).Value = "0"
                ddleditCounty.SelectedValue = objUser.CountyId
            End If

            If Not ddleditStatus Is Nothing Then
                ddleditStatus.SelectedValue = status
            End If
        End If

        Dim ddlRole As DropDownList = CType(UserFormView.FindControl("ddlRole"), DropDownList)
        If Not ddlRole Is Nothing Then
            'POPULATE THE ROLE DROPDOWN LIST WITH THE PROPER ROLES FOR THE CURRENT USER
            ddlRole.DataSource = UserSecurity.Role.ListByCreator(UserAuthorization.CurrentUser.RoleId)
            ddlRole.DataBind()
            ddlRole.Enabled = RoleEditable()
            ddlRole.SelectedValue = role
            ddlRole.Attributes.Add("onchange", "javascript: SetUploadHiddenField('" & ddlRole.ClientID & "', '" & Me.UploadHiddenField.ClientID & "'); return false;")
        End If

        Dim ddleditRole As DropDownList = CType(UserFormView.FindControl("ddleditRole"), DropDownList)
        If Not ddleditRole Is Nothing Then

            If roleId = UserSecurity.Role.RoleType.Participant Or roleId = UserSecurity.Role.RoleType.LegalGuardian Or roleId = UserSecurity.Role.RoleType.Representative Then
                'POPULATE THE ROLE DROPDOWN LIST WITH ALL VALUES
                ddleditRole.DataSource = UserSecurity.Role.ListAll()
                ddleditRole.DataBind()
                ddleditRole.SelectedValue = role
                ddleditRole.Enabled = False
            Else
                'POPULATE THE ROLE DROPDOWN LIST WITH THE PROPER ROLES FOR THE CURRENT USER
                ddleditRole.DataSource = UserSecurity.Role.ListByCreator(UserAuthorization.CurrentUser.RoleId)
                ddleditRole.DataBind()
                ddleditRole.Enabled = RoleEditable()
            End If

            ddleditRole.SelectedValue = role
            Me.hfRole.Value = role
            ddleditRole.Attributes.Add("onchange", "javascript: SetUploadHiddenField('" & ddleditRole.ClientID & "', '" & Me.UploadHiddenField.ClientID & "'); return false;")
        End If

    End Sub

    Protected Sub Page_Load(ByVal sender As Object, _
                            ByVal e As System.EventArgs) _
                            Handles Me.Load

        Try
            If Request("msg") IsNot Nothing Then
                SetMessageStatus()
            Else
                ClearStatus()
            End If

            SetupJavaScript()
            If Not IsPostBack Then

                Me.FindUserPanel.Visible = True
                Me.BindDropDowns()

                If Request.QueryString("TYPE") IsNot Nothing Then
                    'Me.RoleDropDownList.SelectedItem = GetRoleItem(Request.QueryString("TYPE"))
                    Me.RoleDropDownList.SelectedValue = GetRoleItem(Request.QueryString("TYPE"))
                Else
                    Me.SetFormPermissons()
                End If

            End If

            SetAgencyDropDown()


            If ErrorSummary.Visible = True Then
                ErrorSummary.Visible = False
            End If

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the Page_Load() method.", ex)
        End Try

    End Sub

    Private Sub SetMessageStatus()
        Select Case CStr(Request("msg")).ToLower()
            Case "assign"
                SetStatus("Agency Assigned.")
            Case "submit"
                SetStatus("User information saved.")
        End Select
    End Sub

    Private Sub SetupJavaScript()

        EntityController.JavaScriptAddChildDiv(Me.UsersScrollingGridView.DivClientId, CInt(Me.UsersScrollingGridView.ToolTip))
        EntityController.JavaScriptAddChildDiv(Me.AddEditUserPanel.ClientID, CInt(Me.AddEditUserPanel.ToolTip))
        ClientScript.RegisterStartupScript(Me.GetType(), "scrollDivs", EntityController.JavaScriptScrollingGridStartup(Me.UsersScrollingGridView), True)
        'EntityController.JavaScriptAddChildDiv("UserSearchDiv", 100)
        EntityController.JavaScriptSetFixedHeight(30)
    End Sub

    Private Sub SetStatus(ByVal message As String)
        Dim mymaster As ASP.admin_admin_master = CType(Me.Master, ASP.admin_admin_master)
        mymaster.SetStatus(message)
    End Sub
    Private Sub ClearStatus()
        SetStatus("")
    End Sub

    ''' <summary>
    ''' Determines whether the agencies button and the agency button should be visible and/or enabled
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SetAgencyDropDown()
        Dim selectedRole As Role.RoleType = CType(RoleDropDownList.Value, Role.RoleType)
        Dim currentUserRole As Role.RoleType = CType(UserAuthorization.CurrentUser.RoleId, Role.RoleType)

        Select Case currentUserRole
            Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin, _
            UserSecurity.Role.RoleType.LocalProgramUser, UserSecurity.Role.RoleType.SupportBroker, _
            UserSecurity.Role.RoleType.SupportBrokerAdmin
                Me.SubmitRoleButton.Visible = False
                PopulateAgencyUserDropDown(currentUserRole)
                Me.AgencyDropDownList.Editable = False
            Case UserSecurity.Role.RoleType.SysAdmin, UserSecurity.Role.RoleType.StateAdmin
                Me.RoleDropDownList.AddDropddownAttribute("onchange", "javascript:SetAgencyVisible('" & RoleDropDownList.DropDownClientId & "', '" & Me.SubmitRoleButton.ClientID & "');")
        End Select



        If RoleDropDownList.Value.Equals("0") Then
            Me.SubmitRoleButton.Style("visibility") = "hidden"
        Else

            Select Case selectedRole
                Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin, _
                 UserSecurity.Role.RoleType.LocalProgramUser, UserSecurity.Role.RoleType.SupportBroker, _
                 UserSecurity.Role.RoleType.SupportBrokerAdmin
                    Me.SubmitRoleButton.Style("visibility") = "visible"
                Case Else
                    Me.SubmitRoleButton.Style("visibility") = "hidden"
            End Select
        End If
    End Sub
    ''' <summary>
    ''' Agency Dropdown
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub PopulateAgencyUserDropDown(ByVal currentRole As Role.RoleType)
        Select Case currentRole
            Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin
                Dim currentFMSAUser As Cdm.DataCore.Entities.FMSAUser = Cdm.DataCore.Entities.FMSAUser.RetrieveByUserId(UserAuthorization.CurrentUser.UserId)
                If currentFMSAUser.FMSAId > 0 Then
                    Dim FMSAAgency As Cdm.DataCore.Entities.FMSA = Cdm.DataCore.Entities.FMSA.Retrieve(currentFMSAUser.FMSAId)
                    Me.AgencyDropDownList.Items.Add(New ListItem(FMSAAgency.AgencyName, FMSAAgency.FMSAId))
                End If
            Case UserSecurity.Role.RoleType.SupportBroker, UserSecurity.Role.RoleType.SupportBrokerAdmin
                Dim currentSBUser As Cdm.DataCore.Entities.SupportBroker = Cdm.DataCore.Entities.SupportBroker.RetrieveByUserId(UserAuthorization.CurrentUser.UserId)
                If currentSBUser.SupportBrokerAgencyId > 0 Then
                    Dim sbAgency As Cdm.DataCore.Entities.SupportBrokerAgency = Cdm.DataCore.Entities.SupportBrokerAgency.Retrieve(currentSBUser.SupportBrokerAgencyId)
                    Me.AgencyDropDownList.Items.Add(New ListItem(sbAgency.AgencyName, sbAgency.SupportBrokerAgencyId))
                End If
            Case UserSecurity.Role.RoleType.LocalProgramUser
                Dim currentLPUser As Cdm.DataCore.Entities.LocalProgramUser = Cdm.DataCore.Entities.LocalProgramUser.RetrieveByUserId(UserAuthorization.CurrentUser.UserId)
                If currentLPUser.LocalProgramId > 0 Then
                    Dim localProgramOffice As Cdm.DataCore.Entities.LocalProgram = Cdm.DataCore.Entities.LocalProgram.Retrieve(currentLPUser.LocalProgramId)
                    Me.AgencyDropDownList.Items.Add(New ListItem(localProgramOffice.LocalProgramName, localProgramOffice.LocalProgramId))
                End If
        End Select
    End Sub

    Protected Sub btnAssign_Click(ByVal sender As Object, _
                                  ByVal e As System.EventArgs) _
                                  Handles btnAssign.Click
        Try

            Dim ddlAgency As DropDownList = CType(Me.pnlAgency.FindControl("ddlAgency"), DropDownList)
            Dim iAgencyId As Integer
            Dim iUserId As Integer = Convert.ToInt32(Me.hfUserId.Value)
            Dim iRoleId As Integer = Convert.ToInt32(Me.hfRole.Value)
            Dim blnUseAgencyAddress As Boolean = Convert.ToBoolean(Me.hfUseAgencyAddress.Value)
            Dim blnUseAsMailingAddress As Boolean = Convert.ToBoolean(Me.hfUseAsMailingAddress.Value)
            Dim sProvider As String

            If Not IsNumeric(ddlAgency.SelectedValue) Then
                formError("Please select an agency or select none.")
                Exit Sub
            Else
                iAgencyId = Convert.ToInt32(ddlAgency.SelectedValue)
            End If

            If iRoleId = Cdm.DataCore.UserSecurity.Role.RoleType.FMSAAdmin Or _
                iRoleId = Cdm.DataCore.UserSecurity.Role.RoleType.FMSA Then

                Dim objFMSAAgent As Cdm.DataCore.Entities.FMSAUser

                'CHECK IF ENTITY EXISTS ALREADY FOR THIS USERID
                Try
                    objFMSAAgent = FMSAUser.RetrieveByUserId(iUserId)
                Catch ex As Exception
                    objFMSAAgent = New Cdm.DataCore.Entities.FMSAUser()
                End Try

                objFMSAAgent.FMSAId = iAgencyId
                objFMSAAgent.UserId = iUserId
                objFMSAAgent.DateModified = Now()
                objFMSAAgent.LastModified = UserAuthorization.CurrentUser.LogonId
                objFMSAAgent.Persist()
                If iAgencyId > 0 Then
                    SetStatus("Agency information saved.")
                Else
                    SetStatus("User information saved.")
                End If

                If blnUseAgencyAddress Then
                    'ASSIGN ADDRESS TO USER RECORD
                    Me.AssignAgencyAddress(iRoleId, iAgencyId, iUserId, blnUseAsMailingAddress)
                End If

            ElseIf iRoleId = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker Or _
                iRoleId = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin Then

                'If (iAgencyId = 0) And (Me.txtProvider.Text = "") Then
                '    formError("A medicaid number needs to be provided for this user.")
                '    Exit Sub
                'End If

                If txtProvider.Text <> "" Then
                    sProvider = Me.txtProvider.Text.Trim()
                Else
                    sProvider = String.Empty
                End If

                Dim objSB As Cdm.DataCore.Entities.SupportBroker

                'CHECK IF ENTITY EXISTS ALREADY FOR THIS USERID
                Try
                    objSB = SupportBroker.RetrieveByUserId(iUserId)
                Catch ex As Exception
                    objSB = New Cdm.DataCore.Entities.SupportBroker()
                End Try

                objSB.SupportBrokerAgencyId = iAgencyId
                objSB.MedicaidNumber = sProvider
                objSB.UserId = iUserId
                objSB.DateModified = Now()
                objSB.LastModified = UserAuthorization.CurrentUser.LogonId
                objSB.Persist()

                If iAgencyId > 0 Then
                    SetStatus("Agency information saved.")
                Else
                    SetStatus("User information saved.")
                End If

                If blnUseAgencyAddress Then
                    'ASSIGN ADDRESS TO USER RECORD
                    Me.AssignAgencyAddress(iRoleId, iAgencyId, iUserId, blnUseAsMailingAddress)
                End If

                If Me.UploadHiddenField.Value = "1" Then
                    Me.Upload(objSB.UserId)
                End If

            ElseIf iRoleId = Cdm.DataCore.UserSecurity.Role.RoleType.LocalProgramUser Then

                Dim objLP As Cdm.DataCore.Entities.LocalProgramUser

                'CHECK IF ENTITY EXISTS ALREADY FOR THIS USERID
                Try
                    objLP = LocalProgramUser.RetrieveByUserId(iUserId)
                Catch ex As Exception
                    objLP = New Cdm.DataCore.Entities.LocalProgramUser()
                End Try

                objLP.LocalProgramId = iAgencyId
                objLP.UserId = iUserId
                objLP.DateModified = Now()
                objLP.LastModified = UserAuthorization.CurrentUser.LogonId
                objLP.Persist()
                If iAgencyId > 0 Then
                    SetStatus("Agency information saved.")
                Else
                    SetStatus("User information saved.")
                End If

            End If

            Me.pnlAgency.Visible = False
            Me.UsersObjectDataSource.Select()
            UsersScrollingGridView.DataBind()
            Me.FindUserPanel.Visible = True

            ' Response.Redirect("users.aspx?msg=assign", True)
            Me.UsersScrollingGridView.Visible = False

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the btnAssign_Click() method.", ex)
        End Try
    End Sub

    Protected Sub ddlAgency_SelectedIndexChanged(ByVal sender As Object, _
                                                 ByVal e As System.EventArgs) _
                                                 Handles ddlAgency.SelectedIndexChanged

        If (Me.ddlAgency.SelectedValue = "0") And (Me.hfRole.Value = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker) Then
            Me.lblProvider.Visible = True
            Me.txtProvider.Visible = True
        ElseIf (Me.ddlAgency.SelectedValue = "0") And (Me.hfRole.Value = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin) Then
            Me.lblProvider.Visible = True
            Me.txtProvider.Visible = True
        Else
            Me.lblProvider.Visible = False
            Me.txtProvider.Visible = False
        End If

    End Sub

    Protected Sub RoleDropDownList_SelectedIndexChanged() Handles RoleDropDownList.SelectedIndexChanged

    End Sub

    Protected Sub SearchButton_Click(ByVal sender As Object, _
                                     ByVal e As System.EventArgs) _
                                     Handles SearchButton.Click

        Try

            Dim firstName As String
            Dim lastName As String
            Dim roleId As Integer
            Dim agencyId As Integer

            'CHECK IF SEARCH CRITERIA IS ENTERED
            If Me.ValidateSearchCriteria() Then
                firstName = Me.FirstNameTextBox.Value.Trim()
                lastName = Me.LastNameTextBox.Value.Trim()

                Try
                    roleId = CType(Me.RoleDropDownList.Value, Integer)
                Catch ex As Exception
                    roleId = 0
                End Try

                Try
                    agencyId = CType(Me.AgencyDropDownList.Value, Integer)
                Catch ex As Exception
                    agencyId = 0
                End Try
                Dim currentUserRoleId As Integer = UserAuthorization.CurrentUser.RoleId
                Me.UsersScrollingGridView.DataSource = UserSecurity.CDMUser.Search(firstName, lastName, roleId, agencyId, currentUserRoleId)
                Me.UsersScrollingGridView.DataBind()
                Me.UsersScrollingGridView.Visible = True
            Else
                Me.formError("Please enter search criteria")
            End If

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the SearchButton_Click() method.", ex)
        End Try

    End Sub

    Protected Sub CheckBoxAgencyAddress_CheckedChanged(ByVal sender As Object, _
                                                        ByVal e As System.EventArgs)

        Try
            Dim checkBoxUseAgencyAddress As CheckBox = CType(Me.UserFormView.FindControl("CheckBoxAgencyAddress"), CheckBox)
            'Response.Write("<h3>==>" & checkBoxUseAgencyAddress.Checked & "<==</h3>")

            'Me.PopulateMailingAddress(checkBoxUseAgencyAddress.Checked)
            Me.hfUseAgencyAddress.Value = checkBoxUseAgencyAddress.Checked

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the CheckBoxAgencyAddress_CheckedChanged() method.", ex)
        End Try

    End Sub

    Protected Sub CheckBoxMailingAddress_CheckedChanged(ByVal sender As Object, _
                                                        ByVal e As System.EventArgs)

        Try
            Dim checkBoxUseMailingAddress As CheckBox = CType(Me.UserFormView.FindControl("CheckBoxMailingAddress"), CheckBox)
            Dim checkBoxUseAgencyAddress As CheckBox = CType(Me.UserFormView.FindControl("CheckBoxAgencyAddress"), CheckBox)

            If Me.hfUseAgencyAddress.Value = "true" Then
                Me.PopulateMailingAddress(False)
            Else
                Me.PopulateMailingAddress(checkBoxUseMailingAddress.Checked)
            End If

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the CheckBoxMailingAddress_CheckedChanged() method.", ex)
        End Try

    End Sub

    Protected Sub CheckBoxEditMailingAddress_CheckedChanged(ByVal sender As Object, _
                                                            ByVal e As System.EventArgs)

        Try
            Dim checkBoxUseMailingAddress As CheckBox = CType(Me.UserFormView.FindControl("CheckBoxEditMailingAddress"), CheckBox)

            Me.PopulateMailingAddress(checkBoxUseMailingAddress.Checked)

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the CheckBoxEditMailingAddress_CheckedChanged() method.", ex)
        End Try
    End Sub


    Protected Sub ConfirmRoleChangeButton_Click(ByVal sender As Object, _
                                                ByVal e As System.EventArgs) _
                                                Handles ConfirmRoleChangeButton.Click

        Try

            Me.panelChangeRoleVerification.Visible = False
            Me.hfRoleChangeVerified.Value = "True"
            Me.SubmitButton.Enabled = True
            Me.CancelButton.Enabled = True
            Me.SubmitButton_Click(sender, e)

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the ConfirmRoleChangeButton_Click() method.", ex)
        End Try

    End Sub

    Protected Sub CancelRoleChangeButton_Click(ByVal sender As Object, _
                                               ByVal e As System.EventArgs) _
                                               Handles CancelRoleChangeButton.Click

        Try

            Me.panelChangeRoleVerification.Visible = False
            Me.hfRoleChangeVerified.Value = "False"
            Me.SubmitButton.Enabled = True
            Me.CancelButton.Enabled = True

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the CancelRoleChangeButton_Click() method.", ex)
        End Try

    End Sub

    Protected Sub Upload(ByVal userId As Integer)

        If Me.NewFileUploadControl.HasFile Then

            Dim supportBroker As Cdm.DataCore.Entities.SupportBroker = Cdm.DataCore.Entities.SupportBroker.RetrieveByUserId(userId)
            Dim directoryPath As String = Server.MapPath("../Files/SupportBrokerInfo")
            Dim addInfoFile As String = directoryPath & "\" & Me.NewFileUploadControl.FileName.Substring(0, Me.NewFileUploadControl.FileName.IndexOf(".")) & "_" & supportBroker.UserId.ToString & ".doc"

            Dim file As New FileInfo(addInfoFile)
            If file.Exists Then
                file.Delete()
            End If

            supportBroker.AdditionalInfoFile = addInfoFile
            supportBroker.Persist()
            Me.NewFileUploadControl.SaveAs(addInfoFile)
            SetStatus("Support Broker Information added.")
        End If

    End Sub

#End Region

    Protected Sub SubmitRoleButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitRoleButton.Click

        Try

            Dim roleId As Integer = CType(Me.RoleDropDownList.Value, Integer)

            'HIDE THE PREVIOUS GRIDVIEW RESULTS
            Me.UsersScrollingGridView.Visible = False

            Select Case (roleId)
                Case UserSecurity.Role.RoleType.SysAdmin
                    Me.ToggleAgencyVisibility(False, False, True)
                Case UserSecurity.Role.RoleType.FMSA, UserSecurity.Role.RoleType.FMSAAdmin
                    Me.ToggleAgencyVisibility(True, True, True)
                    Me.PopulateAgencyDropDownList(roleId)
                Case UserSecurity.Role.RoleType.SupportBroker, UserSecurity.Role.RoleType.SupportBrokerAdmin
                    Me.ToggleAgencyVisibility(True, True, True)
                    Me.PopulateAgencyDropDownList(roleId)
                Case UserSecurity.Role.RoleType.LocalProgramUser
                    Me.ToggleAgencyVisibility(True, True, True)
                    Me.PopulateAgencyDropDownList(roleId)
                Case Else
                    Me.ToggleAgencyVisibility(False, False, True)
            End Select

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the RoleDropDownList_SelectedIndexChanged() method.", ex)
        End Try

    End Sub

    Protected Sub UsersScrollingGridView_DataBound(ByVal sender As Object, ByVal e As System.EventArgs) Handles UsersScrollingGridView.DataBound
        AccessibilityController.AddImageToSortableGridHeaders(UsersScrollingGridView)
    End Sub

    Protected Sub UsersScrollingGridView_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles UsersScrollingGridView.RowCommand
        If e.CommandName.Equals("Delete") Then
            UsersScrollingGridView.EditIndex = -1
            Me.UserFormView.ChangeMode(FormViewMode.Edit)
            Me.AddEditUserPanel.Visible = True
        End If
    End Sub

    Protected Sub UsersScrollingGridView_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles UsersScrollingGridView.RowDeleting
        e.Cancel = True
    End Sub

    Protected Sub UsersScrollingGridView_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles UsersScrollingGridView.RowEditing
        e.Cancel = True

        Me.FindUserPanel.Visible = False

        SubmitButton.Text = "Update"
        Me.SubmitButton.Visible = True
        Me.CancelButton.Visible = True

        Dim keys As DataKeyArray = UsersScrollingGridView.DataKeys
        Dim iIdx As Integer = e.NewEditIndex

        role = keys.Item(iIdx).Values.Item(1).ToString()

        If UsersScrollingGridView.Rows(iIdx).Cells(3).Text = "&nbsp;" Then
            status = "Inactive"
        Else
            status = UsersScrollingGridView.Rows(iIdx).Cells(3).Text
        End If

        Dim iRow As Integer = e.NewEditIndex
        key = keys.Item(iRow).Value.ToString()

        Me.UserFormObjectDataSource.SelectParameters.Item(0).DefaultValue = key
        Me.UserFormObjectDataSource.Select()

        If Me.RoleDropDownList.Value = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBroker Or _
           Me.RoleDropDownList.Value = Cdm.DataCore.UserSecurity.Role.RoleType.SupportBrokerAdmin Then
            Me.UploadHiddenField.Value = "1"
        Else
            Me.UploadHiddenField.Value = "0"
        End If

        Try
            Me.UserFormView.DataBind()
        Catch aoex As ArgumentOutOfRangeException
            'do nothing
        End Try

        Me.UserFormView.ChangeMode(FormViewMode.Edit)
        Me.AddEditUserPanel.Visible = True

        Me.UserFormView.Visible = True
        UsersScrollingGridView.EditIndex = -1
    End Sub

    Protected Sub UsersScrollingGridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles UsersScrollingGridView.Sorting
        Try

            Dim firstName As String
            Dim lastName As String
            Dim roleId As Integer
            Dim agencyId As Integer
            Dim sortAscending As Boolean = True

            'CHECK IF SEARCH CRITERIA IS ENTERED
            If Me.ValidateSearchCriteria() Then
                firstName = Me.FirstNameTextBox.Value.Trim()
                lastName = Me.LastNameTextBox.Value.Trim()

                Try
                    roleId = CType(Me.RoleDropDownList.Value, Integer)
                Catch ex As Exception
                    roleId = 0
                End Try

                Try
                    agencyId = CType(Me.AgencyDropDownList.Value, Integer)
                Catch ex As Exception
                    agencyId = 0
                End Try

                If Me.hfSortExpression.Value = e.SortExpression Then

                    If Me.hfSortDirection.Value = "ASC" Or Me.hfSortDirection.Value = "" Then
                        Me.hfSortDirection.Value = "DESC"
                    Else
                        Me.hfSortDirection.Value = "ASC"
                    End If

                Else

                    Me.hfSortExpression.Value = e.SortExpression
                    Me.hfSortDirection.Value = "ASC"

                End If

                If Me.hfSortDirection.Value = "ASC" Then
                    sortAscending = True
                Else
                    sortAscending = False
                End If

                Dim currentUserRoleId As Integer = UserAuthorization.CurrentUser.RoleId
                Me.UsersScrollingGridView.DataSource = UserSecurity.CDMUser.Search(firstName, lastName, roleId, agencyId, Me.hfSortExpression.Value, sortAscending, currentUserRoleId)
                Me.UsersScrollingGridView.DataBind()
                Me.UsersScrollingGridView.Visible = True
            Else
                Me.formError("Please enter search criteria")
            End If

        Catch ex As Exception
            ErrorLog(_CLASS_NAME, "An error occurred in the UsersScrollingGridView_Sorting() method.", ex)
        End Try
    End Sub
End Class
